/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.manuscripts.tools;

import cz.mzk.oai.metadataRepository.repository.RecordAnalyzer.BeforeAfterDecision;
import cz.mzk.oai.metadataRepository.repository.Repository;
import cz.mzk.oai.metadataRepository.repository.collections.MetadataCollection;
import cz.mzk.oai.metadataRepository.repository.collections.NoCollectionFoundException;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
public class CollectionDeterminant {

    private final Repository repository;
    private final TeiManager teiManager;

    CollectionDeterminant(Repository repository, TeiManager teiManager) {
        this.repository = repository;
        this.teiManager = teiManager;
    }

    MetadataCollection chooseCollection(Manuscript mns, MetadataCollection originalCollection) throws Exception {
        String signature = mns.getSignature();
        String baseName = chooseBaseName(mns.getSignature());
        BeforeAfterDecision beforeAfter = determineBeforeAfterDecision(originalCollection);
        boolean hasStructuralMetadata = teiManager.isDigitized(signature);
        String collectionName = buildCollectionName(baseName, beforeAfter, hasStructuralMetadata);
        MetadataCollection result = repository.findCollection(collectionName);
        if (result == null) {
            throw new NoCollectionFoundException("No such collection '" + collectionName + "'");
        }
        return result;
    }

    private String chooseBaseName(String signature) throws NoCollectionFoundException {
        if (signature.startsWith("Moll-RKP-") || signature.startsWith("RKP2-0047.948,")) {
            return "rkp_Moll";
        } else {
            return "rkp_unclassified";
        }
        //throw new NoCollectionFoundException("Cannot find collection base name");
    }

    private BeforeAfterDecision determineBeforeAfterDecision(MetadataCollection originalCollection) {
        String name = originalCollection.getName();
        if (name.contains("Before1800")) {
            return BeforeAfterDecision.BEFORE;
        } else if (name.contains("After1800")) {
            return BeforeAfterDecision.AFTER;
        } else {
            return BeforeAfterDecision.ERROR;
        }
    }

    private String buildCollectionName(String baseName, BeforeAfterDecision beforeAfter, boolean structural) {
        StringBuilder result = new StringBuilder();
        result.append(baseName);
        switch (beforeAfter) {
            case BEFORE:
                result.append("_before1800");
                break;
            case AFTER:
                result.append("_after1800");
                break;
            case ERROR:
                result.append("_error1800");
                break;
        }
        if (structural) {
            result.append("_struct");
        } else {
            result.append("_notStruct");
        }
        return result.toString();
    }
}
